package com.jeesite.modules.utils;

import com.jeesite.modules.auth.entity.AuthUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * Redis工具类
 * 用于操作Redis缓存
 */
@Component
public class RedisUtils {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    // Token前缀
    private static final String TOKEN_PREFIX = "token:";
    private static final String REFRESH_TOKEN_PREFIX = "refresh_token:";
    private static final String USER_PREFIX = "user:";

    /**
     * 存储Token
     */
    public void setToken(String username, String token, long expireTime) {
        String key = TOKEN_PREFIX + username;
        redisTemplate.opsForValue().set(key, token, expireTime, TimeUnit.SECONDS);
    }

    /**
     * 获取Token
     */
    public String getToken(String username) {
        String key = TOKEN_PREFIX + username;
        Object token = redisTemplate.opsForValue().get(key);
        return token != null ? token.toString() : null;
    }

    /**
     * 删除Token
     */
    public void deleteToken(String username) {
        String key = TOKEN_PREFIX + username;
        redisTemplate.delete(key);
    }

    /**
     * 存储刷新Token
     */
    public void setRefreshToken(String username, String refreshToken, long expireTime) {
        String key = REFRESH_TOKEN_PREFIX + username;
        redisTemplate.opsForValue().set(key, refreshToken, expireTime, TimeUnit.SECONDS);
    }

    /**
     * 获取刷新Token
     */
    public String getRefreshToken(String username) {
        String key = REFRESH_TOKEN_PREFIX + username;
        Object token = redisTemplate.opsForValue().get(key);
        return token != null ? token.toString() : null;
    }

    /**
     * 删除刷新Token
     */
    public void deleteRefreshToken(String username) {
        String key = REFRESH_TOKEN_PREFIX + username;
        redisTemplate.delete(key);
    }

    /**
     * 存储用户信息（只保存前端需要的字段）
     */
    public void setUser(String username, Object userInfo, long expireTime) {
        String key = USER_PREFIX + username;
        
        // 如果是AuthUser对象，只保存必要字段
        if (userInfo instanceof AuthUser) {
            AuthUser user = (AuthUser) userInfo;
            Map<String, Object> userMap = new HashMap<>();
            userMap.put("id", user.getId());
            userMap.put("username", user.getUsername());
            userMap.put("nickname", user.getNickname());
            userMap.put("password", user.getPassword()); // 加密后的密码
            userMap.put("avatar", user.getAvatar());
            
            redisTemplate.opsForValue().set(key, userMap, expireTime, TimeUnit.SECONDS);
        } else {
            // 兼容其他类型
            redisTemplate.opsForValue().set(key, userInfo, expireTime, TimeUnit.SECONDS);
        }
    }

    /**
     * 获取用户信息
     */
    public Object getUser(String username) {
        String key = USER_PREFIX + username;
        return redisTemplate.opsForValue().get(key);
    }

    /**
     * 删除用户信息
     */
    public void deleteUser(String username) {
        String key = USER_PREFIX + username;
        redisTemplate.delete(key);
    }

    /**
     * 检查Token是否存在
     */
    public boolean hasToken(String username) {
        String key = TOKEN_PREFIX + username;
        return Boolean.TRUE.equals(redisTemplate.hasKey(key));
    }

    /**
     * 检查刷新Token是否存在
     */
    public boolean hasRefreshToken(String username) {
        String key = REFRESH_TOKEN_PREFIX + username;
        return Boolean.TRUE.equals(redisTemplate.hasKey(key));
    }

    /**
     * 设置过期时间
     */
    public void expire(String key, long expireTime) {
        redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
    }

    /**
     * 获取过期时间
     */
    public long getExpire(String key) {
        Long expire = redisTemplate.getExpire(key, TimeUnit.SECONDS);
        return expire != null ? expire : -1;
    }

    /**
     * 检查key是否存在
     */
    public boolean hasKey(String key) {
        return Boolean.TRUE.equals(redisTemplate.hasKey(key));
    }

    /**
     * 删除key
     */
    public void delete(String key) {
        redisTemplate.delete(key);
    }

    /**
     * 清除用户所有相关缓存
     */
    public void clearUserCache(String username) {
        deleteToken(username);
        deleteRefreshToken(username);
        deleteUser(username);
    }
}